Query Randomize Function
What Is the Query Randomize Function?
The Query Randomize user-defined function, queryRandomize, randomizes the rows in a query object so that they are not ordered by anything. Usually it makes sense to order data retrieved from a relational database by a specific column. However, there are times when you do not want to favor any particular column at all. For instance, you might want to list products or people's names in no particular order to avoid showing favoritism; or you might want to pick a single row of data at random. Because queryRandomize orders queries differently each time you call it, any particular row of a query returned by queryRandomize will always be in a random position.
Installing the Query Randomize Function
The Query Randomize function can be used just like any other user-defined function. You can embed the function right into the page where you call it. However we recommend leaving the function in its own file and using the cfinclude tag to include the function in your page.
For instance, if queryRandomize were contained in a file called queryRandomize.cfm in a directory called cf_functions located in your web root, you would include the function in your page like this:
<cfinclude template="/cf_functions/queryRandomize.cfm"/>
Using the Query Randomize Function
You use the Query Randomize function by either imbedding it in your page or including it as described above, and then simply calling it like any other function. You pass in the query that you want to be randomized and it returns a new query containing all the same data but in random order. Note that the columns are not affected by queryRandomize, only the order of the query's rows.
Invoke queryRandomize like this:
<cfinclude template="/cf_functions/queryRandomize.cfm"/>
<cfquery datasource="myDatasource" name="myQuery">
SELECT * FROM MyTable
</cfquery>
<cfset mixedUpQuery = queryRandomize(myQuery)/>
<cfoutput query="mixedUpQuery">
<!--- Output data in a random order. --->
</cfoutput>
How the Query Randomize Function Works
The Query Randomize function works by creating an array of integers called numberBank that is the same size as the original query object. It builds a new query, selecting a row from the original query that corresponds to a randomly chosen number between one and the length of the numberBank array. The numberBank array then gets truncated by one and the process repeats itself for every row in the original query.